<template>
  <!-- 没有目录： -->
  <!-- 应版权方要求 请下载APP阅读 -->
  <!-- 还有个好像是 下架 -->
  <el-container v-wechat-title="book.name || '书籍详细信息'">
    <el-header>
      <nav-bar :loginDialogState="loginDialogState"></nav-bar>
    </el-header>
    <el-main>
      <div>
        <div>
          <div>{{ book.name }}</div>
          <div style="display: block;width: 500px;">
            <el-tag v-for="(tag, index) in book.tags" :type="tagType[index%5]" style="margin: 5px;">{{ tag.name }}</el-tag>
          </div>
          <div>
            <el-image :src="book.imgUrl"></el-image>
            <button @click="addShelfClick(book)">{{ addShelfValue }}</button>
          </div>
          <div>{{ book.author }}</div>
        </div>
        <div>{{ book.minor }}</div>
        <div>{{ book.totalWords}}</div>
        <div>{{ book.finalDate }}</div>
        <div v-for="d in book.data">
          <div>{{ d.key }}</div>
          <div>{{ d.value }}</div>
        </div>
        <div>{{ book.desc }}</div>
      </div>
      <!-- <div>{{ $route.params.bookId }}</div> -->
      <div v-for="chapter in newChapters" :key="chapter.index">
        <div><a @click="chapterClick(chapter.index)">{{ chapter.name }}</a></div>
      </div>
      <p>-------------------------------------------</p>
      <div v-for="chapter in chapters" :key="chapter.index">
        <div><a @click="chapterClick(chapter.index)">{{ chapter.name }}</a></div>
      </div>
    </el-main>
  </el-container>

</template>

<script lang="ts">
import { ref, reactive, defineComponent, onMounted, watch, computed } from "vue"
import { useRouter, useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from "vue-router"
import service from "@/utils/request"
import { addBookshelf, removeFromBookshelf, existBook, EXIST_KEY } from "@/api/axios/Bookshelf"
import { useStore } from "vuex"
import { CODE_KEY, CODE_SUCCESS } from "@/api/params"
import NavBar from "@c/navBar/NavBar.vue"

export default defineComponent ({
  name: "bookContent",
  components:{
    NavBar
  },
  setup () {
    
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    
    const chapters = ref([
      {
        // 章节名
        name: '',
        // 代表第几章
        index: ''
      }
    ])
    const newChapters = ref([
      {
        // 同上
        name: '',
        // 同上
        index: '',
      }
    ])
    const book = reactive ({
      // 书的id
      id: '',
      // 书名
      name: '',
      // 标签
      tags: [
        {
          // 标签名
          name: '',
          // 官网样式
          style: ''
        }
      ],
      // 封面图片链接
      imgUrl: '',
      // 作者名
      author: '',
      // 小类别
      minor: '',
      // 总字数
      totalWords: '',
      // 最后更新日期
      finalDate: '',
      // 数据 包含: 追书人数，读者留存率，日更新字数
      data: [
        {
          key: '',
          value: ''
        }
      ],
      // 简介
      desc: ''
    })
    
    const SHELF_EXIST = "移出书架";
    const SHELF_NOT_EXIST = "加入书架";
    
    const addShelfValue = ref(SHELF_NOT_EXIST)
    
    const loginDialogState = reactive({
      name: 'login',
      visible: false
    })
    
    const addShelfClick = (book) => {
      
      let username = store.getters.getUserInfo.username
      if(!username) {
        // 弹出登录框
        loginDialogState.visible = true
        return;
      }
      // 在书架
      if(addShelfValue.value === SHELF_EXIST) {
        // 移除
        removeFromBookshelf(username, book.id).then(res => {
          if(res && res.data[CODE_KEY] === CODE_SUCCESS) {
            addShelfValue.value = SHELF_NOT_EXIST
            // 删除 书架 LocalStorage 记录
            console.log("deleteRecord")
            store.commit("removeShelfRecord", { bookId: book.id })
          }
        })
      } 
      // 不在书架
      else if(addShelfValue.value === SHELF_NOT_EXIST) {
        // 添加
        addBookshelf(username, book).then(res => {
          if(res.data[CODE_KEY] === CODE_SUCCESS) {
            addShelfValue.value = SHELF_EXIST,
            // 放入 书架 LocalStorage 记录 ，这里需要 搜 阅读记录 的 LocalStorage，如果有，放到 书架 的 LocalStorage 记录
            store.commit("addShelfRecordFromRead", { bookId: book.id})
          }
        })
      }
    }
    
    // 阅读章节
    const chapterClick = (index) => {
      console.log(index)
      // 添加阅读记录
      store.commit("addReadRecord", { book: book, chapterNum: index });
      // 如果在书架里
      if(addShelfValue.value === SHELF_EXIST) {
        console.log("ready in addShelfcord")
        // 放入 书架 LocalStorage 记录 
        store.commit("addShelfRecord", { bookId: book.id, chapterNum: index })
      }
      // 跳转
      router.push(route.path + '/' + parseInt(index));
    }
    
    const exist = () => {
      // 先赋值 不在书架 因为可能 再次跳转进 这个页面，页面不变，会再次调用（点击阅读记录）
      addShelfValue.value = SHELF_NOT_EXIST;
      existBook(store.getters.getUserInfo.username, route.params.bookId).then(res => {
        if(res.data[EXIST_KEY] === true) {
          addShelfValue.value = SHELF_EXIST
        } else {
          addShelfValue.value = SHELF_NOT_EXIST
        }
      })
    }
    
    /**
     * 获取页面信息
     */
    const getContent = (path) => {
      service.get(path).then(res => {
        let data = res.data
        chapters.value = data.chapters
        newChapters.value = data.newChapters
        book.id = data.book.id
        book.name = data.book.name
        book.tags = data.book.tags
        book.imgUrl = data.book.imgUrl
        book.minor = data.book.minor
        book.author = data.book.author
        book.totalWords = data.book.totalWords
        book.finalDate = data.book.finalDate
        book.data = data.book.data
        book.desc = data.book.desc
      })
      if(store.getters.getUserInfo.username) {
        exist()
      }
    }
    
    

    onMounted(()=>{
      getContent(route.path)
    })
    
    onBeforeRouteUpdate((to, from, next) => {
      console.log(to)
      if( to != from){
        getContent(to.path)
        next()
      }
    })
    
    const computeUsername = computed({
      get: () => store.state.userInfo.username
    })
    
    watch((computeUsername), (newValue, oldValue) => {
      if(newValue) {
        exist()
      } else {
        addShelfValue.value = SHELF_NOT_EXIST
      }
    })
    
    const tagType = ['', 'success', 'info', 'warning', 'danger']
    
    return {
      chapters,
      newChapters,
      book,
      route,
      tagType,
      addShelfValue,
      addShelfClick,
      loginDialogState,
      chapterClick,
    }
  }
})

</script>

<style>
</style>
